package extensions.android;

import java.io.IOException;

import uclm.extensions.android.R;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import extensions.android.Client.StatusMessageSendable;
import extensions.packet.RequestStartGamePacket;

public class ClientActivity extends Activity implements StatusMessageSendable {
	
	private Client client;
	private TextView _statusBar;
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        final EditText editText = (EditText)findViewById(R.id.editText1);
        
        editText.setText("10.0.2.2");
        Button connectButton = (Button)findViewById(R.id.button1);
        _statusBar = (TextView)findViewById(R.id.textViewStatus);
        
        
        connectButton.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				initClient(editText.getText().toString());
			}
		});

		
        Button startGameButton = (Button)findViewById(R.id.startGameButton);
        startGameButton.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				getClient().sendPacket(new RequestStartGamePacket());
			}
		});
 
    }
    
    public void setStatusMessage(final String str)
    {
    	runOnUiThread(new Runnable() {
			
			@Override
			public void run() {
				_statusBar.setText(_statusBar.getText()+"\n"+str);
			}
		});
    }
    
    private Thread _initClientThread = null;
    
    private void initClient(final String ip)
    {
    	
    	if (_initClientThread != null)
    		return;
    	
    	_initClientThread = new Thread(new Runnable() {
			
			@Override
			public void run() {
				System.out.println("Creando cliente..");
				setStatusMessage("Creando cliente...");
		        try {
					client = new Client(ip, 7888, ClientActivity.this);
					client.connect();
			        System.out.println("Cliente conectado."); 
			        setStatusMessage("Cliente conectado.");
			        
			        client.startReceiveThread();
				} catch (IOException e) {
					e.printStackTrace();
				}

			}
		});
    	
    	_initClientThread.start();
    }
    
    public Client getClient()
    {
    	return client;
    }

	@Override
	public void sendMessage(String msg)
	{
		setStatusMessage(msg);
	}
}